<template>
  <common-card class="knowledge-point">
    <template #title
      >知识点分析
      <span ref="tooltipRef" class="tooltip-wrapper">
        <a-tooltip placement="bottom" :getPopupContainer="() => tooltipRef">
          <template #title>
            <div class="overlay-content">
              <span>薄弱知识点（标红显示）：正确率低于60%的知识点；</span><br />
              <span>未掌握学生数：知识点正确率低于85%的学生数量。</span>
            </div>
          </template>
          <label class="explain-icon"></label>
        </a-tooltip>
      </span>
    </template>
    <!-- <template #operate
      ><span class="operate" @click="goWrongBook"
        ><span class="operate__desc">巩固薄弱项</span
        ><label class="operate__icon"></label></span
    ></template> -->
    <div>
      <p class="type-btn">
        <span class="btn-group"
          ><button
            class="btn"
            :class="{ active: activeType === 'table' }"
            @click="activeType = 'table'"
          >
            表格</button
          ><button
            class="btn"
            :class="{ active: activeType === 'chart' }"
            @click="activeType = 'chart'"
          >
            图表
          </button></span
        >
      </p>
      <div class="table">
        <a-table
          v-show="activeType === 'table'"
          :showSorterTooltip="false"
          :columns="KNOWLEDGE_COLUMN"
          :dataSource="dataList"
          :pagination="false"
          :scroll="{ y: 300 }"
        >
          <template v-slot:bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'knowledge_name'">
              <span
                :style="{ color: record.right_rate < 0.6 ? '#FF7B73' : '' }"
                >{{ record.knowledge_name }}</span
              ></template
            >
            <template v-if="column.dataIndex === 'right_rate'">
              {{ getPercent(record.right_rate) }}%</template
            >
          </template>
        </a-table>
        <ul class="level" v-if="activeType === 'chart'">
          <li
            class="level__item"
            v-for="(item, index) in levelList"
            :key="index"
            @click="currentLevel = index"
            :class="{ active: currentLevel === index }"
          >
            <span class="num">{{ item.num }}个</span>
            <span class="desc">{{ item.desc }}</span>
            <label v-if="item.label" class="label">{{ item.label }}</label>
          </li>
        </ul>
        <NoData
          v-if="activeType === 'chart' && dataList?.length === 0"
        ></NoData>
        <div
          v-show="activeType === 'chart' && dataList?.length > 0"
          ref="barChartRef"
          style="width: 100%%; height: 381px"
        ></div>
      </div>
      <div v-show="props.activeTab === 'grade'">
        <p class="learning-state">
          <span class="title"
            >各班知识点掌握情况
            <span ref="classTooltipRef" class="tooltip-wrapper">
              <a-tooltip
                placement="bottom"
                :getPopupContainer="() => classTooltipRef"
              >
                <template #title>
                  <div class="overlay-content">
                    <span>已掌握：正确率为85%~100%</span><br />
                    <span>待强化：正确率为60%~85%</span><br />
                    <span>未掌握：正确率为0~60%</span>
                  </div>
                </template>
                <label class="explain-icon"></label>
              </a-tooltip> </span
          ></span>
          <span class="operate" @click="goDetail"
            ><span class="operate__desc">详情</span
            ><label class="operate__icon"></label
          ></span>
        </p>
        <NoData v-if="classKnowledgeList?.length === 0"></NoData>
        <div
          v-show="classKnowledgeList?.length && classKnowledgeList?.length > 0"
          class="chart"
          ref="chartRef"
          style="width: 100%; height: 466px"
        ></div>
      </div>
    </div>
  </common-card>
</template>
<script setup>
import CommonCard from '../components/CommonCard.vue'
import { KNOWLEDGE_COLUMN } from '../constant'
import useCharts from '@/utils/echart/index'
import { ref, watchEffect, watch, computed } from 'vue'
import { getPercent } from '../utils'
import { useRouter } from 'vue-router'
import {
  getClassKnowledgeList,
  getGradeKnowledgeList,
  getClassKnowledgePointList
} from '@/apis/situation-report/index'
import { useSituationReport } from '@/stores/situation-report'
const situationReport = useSituationReport()
const router = useRouter()
const props = defineProps({
  activeTab: {
    default: 'garde',
    type: String
  }
})
const activeType = ref('table')
const barChartRef = ref()

const currentLevel = ref(0)
const levelList = ref([
  {
    desc: '0-60%',
    num: 0,
    label: '薄弱',
    children: []
  },
  {
    desc: '60-75%',
    num: 0,
    children: []
  },
  {
    desc: '75-85%',
    num: 0,
    children: []
  },
  {
    desc: '85-95%',
    num: 0,
    children: []
  },
  {
    desc: '95-100%',
    num: 0,
    children: []
  }
])
const tooltipRef = ref(null)
const classTooltipRef = ref(null)
const classKnowledgeList = ref()
const dataList = ref([])
const getBarOption = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      padding: [12, 16],
      borderRadius: 8,
      axisPointer: {
        type: 'shadow',
        label: {
          fontSize: 14,
          shadowColor: 'rgba(139, 200, 254, 0.15)'
        }
      },
      formatter: params => {
        let res = `<span style="font-weight: 700;">${params[0].axisValueLabel}</span><br>`
        params.forEach(item => {
          res += `<span style="display: flex; align-items: center;gap: 28px; padding-top: 16px;">
            <span style="width: 72px; display: inline-flex; align-items: center; gap: 4px">
              <span style="display: inline-block; width: 12px; height: 12px; border-radius: 200px; background: ${
                item.color
              };"></span>
            <span style="color: rgba(4, 11, 26, 0.75);">${
              item.seriesName
            }</span>
          </span>
          <span style="color: rgba(4, 11, 26, 0.5)">${item.data}${
            item.seriesName === '正确率' ? '%' : ''
          }</span>
         </span>`
        })
        return res
      }
    },
    legend: {
      itemGap: 22,
      right: 0
    },
    grid: {
      left: '40',
      right: '50',
      bottom: '18%',
      top: '14%'
    },
    color: ['#8BC8FF'],
    dataZoom: {
      startValue: 0,
      endValue: 6,
      minSpan: levelList.value[currentLevel.value].children?.length
        ? levelList.value[currentLevel.value].children.length < 7
          ? 100
          : parseFloat(
              (
                (6 / levelList.value[currentLevel.value].children.length) *
                100
              ).toFixed(1)
            )
        : 1,
      type: 'slider',
      filterMode: 'none',
      showDetail: false
    },
    xAxis: {
      type: 'category',
      data: levelList.value[currentLevel.value].children?.map(
        item => item.knowledge_name
      ),
      axisLabel: {
        formatter: function (value) {
          let res = value
          if (res.length && res.length > 6) {
            res = res.substring(0, 5) + '..'
          }
          return res || ''
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '正确率',
        interval: 20,
        max: 100,
        nameTextStyle: {
          align: 'right'
        },
        axisLabel: {
          formatter: `{value}%`
        }
      },
      {
        type: 'value',
        name: '题目数',
        splitNumber: 5,
        interval: getMax.value / 5,
        max: getMax.value,
        nameTextStyle: {
          align: 'left'
        }
      }
    ],
    series: [
      {
        data:
          levelList.value[currentLevel.value].children?.map(item =>
            getPercent(item.right_rate)
          ) || [],
        name: '正确率',
        itemStyle: {
          color: '#FFD879'
        },
        label: {
          show: true,
          position: 'top',
          color: '#000',
          formatter: `{c}%`
        },
        symbol: 'circle',
        symbolSize: 14,
        type: 'line',
        yAxisIndex: 0
      },
      {
        data:
          levelList.value[currentLevel.value].children?.map(
            item => item.question_count
          ) || [],
        name: '题目数',
        type: 'bar',
        barMaxWidth: 60,
        itemStyle: {
          borderRadius: [8, 8, 0, 0]
        },
        yAxisIndex: 1
      }
    ]
  }
  return option
}

const getMax = computed(() => {
  const max =
    levelList.value[currentLevel.value].children &&
    levelList.value[currentLevel.value].children.length > 0
      ? Math.max(
          ...levelList.value[currentLevel.value].children.map(
            item => item.question_count
          )
        )
      : 0
  const flag = Math.ceil(max / 5)
  if (max === 1) return 5
  else return flag * 5
})

const getOption = () => {
  const option = {
    color: ['#4CDFC0', '#FFD879', '#FF7B73'],
    tooltip: {
      trigger: 'axis',
      padding: [12, 16],
      borderRadius: 8,
      axisPointer: {
        type: 'shadow',
        label: {
          fontSize: 14,
          shadowColor: 'rgba(139, 200, 254, 0.15)'
        }
      },
      formatter: params => {
        let res = `<span style="font-weight: 700;">${params[0].axisValueLabel}</span><br>`
        params.forEach(item => {
          res += `<span style="display: flex; align-items: center; padding-top: 16px; justify-content: space-between;">
            <span style="width: fit-content; display: inline-flex; align-items: center; gap: 4px">
              <span style="display: inline-block; width: 12px; height: 12px; border-radius: 200px; background: ${item.color};"></span>
            <span style="color: rgba(4, 11, 26, 0.75);">${item.seriesName}</span>
          </span>
          <span style="color: rgba(4, 11, 26, 0.5); width: 50px; display: inline-block; margin-left: 16px;">${item.data}个</span>
         </span>`
        })
        return res
      }
    },
    dataZoom: {
      startValue: 0,
      endValue: 4,
      // 滑动块最小值，百分比0-100
      minSpan: classKnowledgeList.value?.length
        ? classKnowledgeList.value.length < 5
          ? 100
          : parseFloat(((4 / dataList.value.length) * 100).toFixed(1))
        : 1,
      type: 'slider',
      filterMode: 'none',
      showDetail: false
    },
    legend: {
      itemGap: 22,
      left: 0
    },
    xAxis: {
      type: 'category',
      data: classKnowledgeList.value?.map(item => item.class_name) || []
    },
    yAxis: {
      type: 'value'
    },
    grid: {
      left: '1%',
      right: '3%',
      bottom: '12%',
      top: '10%',
      containLabel: true
    },
    series: [
      {
        data: classKnowledgeList.value?.map(item => item.good_count) || [],
        type: 'bar',
        name: '优势知识点',
        barWidth: '24',
        itemStyle: {
          borderRadius: [8, 8, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          color: 'rgba(4, 11, 26, 0.5)'
        }
      },
      {
        data: classKnowledgeList.value?.map(item => item.enhance_count) || [],
        type: 'bar',
        name: '待强化知识点',
        barWidth: '24',
        itemStyle: {
          borderRadius: [8, 8, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          color: 'rgba(4, 11, 26, 0.5)'
        }
      },
      {
        data: classKnowledgeList.value?.map(item => item.weak_count) || [],
        type: 'bar',
        name: '未掌握知识点',
        barWidth: '24',
        itemStyle: {
          borderRadius: [8, 8, 0, 0]
        },
        label: {
          show: true,
          position: 'top',
          color: 'rgba(4, 11, 26, 0.5)'
        }
      }
    ]
  }
  return option
}

const goWrongBook = () => {
  router.push({
    path: '/wrongBook',
    query: {
      source: 'situationReport',
      resourceType: '5',
      resourceTab: '2'
    }
  })
}

watch(
  () => activeType.value,
  val => {
    if (val === 'chart') setGradeOption(getBarOption())
  }
)

watch(
  () => currentLevel.value,
  () => {
    setGradeOption(getBarOption())
  }
)

const getGradeList = async () => {
  const {
    data: { list }
  } = await getGradeKnowledgeList(situationReport.search)
  dataList.value = list || []
  handleData()
}

const handleData = () => {
  levelList.value.forEach(item => {
    item.children = []
    item.num = 0
  })
  dataList.value.forEach(item => {
    if (item.right_rate < 0.6) {
      levelList.value[0].num += 1
      levelList.value[0].children.push(item)
    } else if (item.right_rate < 0.75) {
      levelList.value[1].num += 1
      levelList.value[1].children.push(item)
    } else if (item.right_rate < 0.85) {
      levelList.value[2].num += 1
      levelList.value[2].children.push(item)
    } else if (item.right_rate < 0.95) {
      levelList.value[3].num += 1
      levelList.value[3].children.push(item)
    } else {
      levelList.value[4].num += 1
      levelList.value[4].children.push(item)
    }
  })
}

const goDetail = () => {
  router.push('/masteringSituation')
}

const getClassList = async () => {
  const {
    data: { list }
  } = await getClassKnowledgeList(situationReport.search)
  classKnowledgeList.value = list || []
}
const chartRef = ref(null)
const { setOption: setClassOption } = useCharts(chartRef, true, true, 'light')
const { setOption: setGradeOption } = useCharts(
  barChartRef,
  true,
  true,
  'light'
)
const getClassPointList = async () => {
  const {
    data: { list }
  } = await getClassKnowledgePointList(situationReport.search)
  dataList.value = list || []
  handleData()
}

watchEffect(async () => {
  if (
    situationReport.search.class_id ||
    situationReport.search.grade_id ||
    situationReport.search.subject_id
  ) {
    if (props.activeTab === 'grade') {
      await getGradeList()
      if (activeType.value === 'chart') setGradeOption(getBarOption())
      await getClassList()
      if (classKnowledgeList.value && classKnowledgeList.value?.length > 0) {
        setClassOption(getOption())
      }
    } else {
      await getClassPointList()
      if (activeType.value === 'chart') setGradeOption(getBarOption())
    }
  }
})
</script>
<style lang="less" scoped>
@import '../style.less';

.knowledge-point {
  .operate {
    &__icon {
      margin-left: 4px;
      background: url('@/assets/images/situation-report/right-arrow.png')
        no-repeat center/cover;
    }
  }

  .learning-state {
    margin-top: @gap;
    display: flex;
    justify-content: space-between;

    .title {
      display: inline-flex;
      align-items: center;
      font-weight: 700;
    }
  }

  .type-btn {
    text-align: right;

    .btn-group {
      display: inline-flex;
      gap: 16px;
      border: 1px solid #e6e7e8;
      border-radius: @small-radius;
      padding: 4px 8px;
      justify-content: space-between;

      .btn {
        padding: 4px 16px;
        border-radius: @small-radius;
        border: none;
        background: unset;

        &.active {
          font-weight: 700;
          background: #c8daff;
          color: #4d88ff;
        }
      }
    }
  }

  .table {
    margin-top: @gap;
  }

  .level {
    display: flex;
    justify-content: center;
    gap: @gap;

    li {
      list-style-type: none;
    }

    &__item {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;
      cursor: pointer;

      &.active {
        * {
          color: #4d88ff !important;
        }

        .desc {
          position: relative;
          display: inline-block;

          &::after {
            content: '';
            position: absolute;
            bottom: -3px;
            width: 8px;
            height: 3px;
            left: calc(50% - 4px);
            background: #0079ff;
          }
        }
      }

      .num {
        font-weight: 800;
        font-size: @base-size;
        color: @minor-font-color;
      }

      .desc {
        color: @not-important-font-color;
        font-weight: 500;
        font-size: 14px;
      }

      .label {
        display: inline-flex;
        align-items: center;
        padding: 2px 4px;
        border-radius: 4px;
        background: #ffefee;
        color: #ff7b73 !important;
        font-size: 12px;
        margin-top: 10px;
      }
    }
  }

  .chart {
    margin-top: @gap;
  }
}
</style>
